package com.hunantv.mglive.ui.act;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ParticiPatorModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.VODModel;
import com.hunantv.mglive.ui.discovery.MaxSeekBar;
import com.hunantv.mglive.utils.HttpUtils;
import com.hunantv.mglive.utils.MGTVUtil;
import com.hunantv.mglive.utils.ReportUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.widget.media.IjkVideoView;
import com.hunantv.mglive.widget.media.VideoController;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by June Kwok on 2016-1-27.
 */
public class ActCard extends FrameLayout implements HttpUtils.callBack {
    private HttpUtils mHttp;
    private ParticiPatorModel mData;
    private String mVideoPath = "";
    private LayoutInflater mInflater;
    public CardViewHolder mCard;
    boolean isVideoStared = false, isAnimaStared = false;
    private String mStageAction;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    start();
                    break;
                case 1:
                    stop();
                    break;
                default:
                    break;
            }
        }
    };

    public void startVideo() {
        isVideoStared = true;
        if (StringUtil.isNullorEmpty(mVideoPath)) {
            return;
        }
        if (null != mHandler) {
            mHandler.sendEmptyMessageDelayed(0, 200);
        }
    }

    public void stopVideo() {
        isVideoStared = false;
        if (null != mHandler) {
            mHandler.sendEmptyMessageDelayed(1, 10);
        }
    }

    public void start() {
        if (null == mCard || null == mCard.mVideoView) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("auid", mData.getUid());
        params.put("mid", mData.getVideoId());
        params.put("ap", "1");
        mCard.mVideoView.setVideoPath(mVideoPath, params, IjkVideoView.VideoType.vod);
        mCard.mVideoView.requestFocus();
        mCard.mVideoView.start();
    }

    public void continuePlay() {
        if (null == mCard || null == mCard.mVideoView || mCard.mVideoView.isPlaying() || StringUtil.isNullorEmpty(mVideoPath)) {
            return;
        }
        mCard.mVideoView.start();
    }

    public void pause() {
        if (null != mCard && null != mCard.mVideoView && mCard.mVideoView.isPlaying()) {
            mCard.mVideoView.pause();
        }
    }

    public void stop() {
        if (null != mCard && null != mCard.mVideoView) {
            try {
                mCard.mVideoView.stopBackgroundPlay();
            } catch (Exception e) {

            }
            try {
                mCard.mVideoView.stopPlayback();
            } catch (Exception e) {

            }
        }
    }

//    public ActCard(Context context, ParticiPatorModel mData, String title, int delayMills) {
//        super(context);
//        mHttp = new HttpUtils(context, this);
//        this.mData = mData;
//        mInflater = LayoutInflater.from(context);
//        setStageAction(title);
//        initView();
//        loadData(delayMills);
//    }

    public ActCard(Context context, ParticiPatorModel mData, String title) {
        super(context);
        mHttp = new HttpUtils(context, this);
        this.mData = mData;
        mInflater = LayoutInflater.from(context);
        setStageAction(title);
        initView();
        loadData();
    }

    private void initView() {
        View view = mInflater.inflate(R.layout.act_card_content, this, false);
        LayoutParams mViewLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mViewLP.gravity = Gravity.CENTER;
        addView(view, mViewLP);
        initViewHolder(view);
    }

    private void initViewHolder(View view) {
        mCard = new CardViewHolder();
        mCard.mVideoParent = (FrameLayout) view.findViewById(R.id.act_pk_video_parent);
        mCard.mVideoView = (IjkVideoView) view.findViewById(R.id.act_pk_video_part);
        mCard.mVideoCover = (ImageView) view.findViewById(R.id.act_pk_video_cover);
        FrameLayout.LayoutParams mCoverLP = (FrameLayout.LayoutParams) mCard.mVideoCover.getLayoutParams();
        mCoverLP.width = Constant.toPix(720);
        mCard.mVideoCover.setLayoutParams(mCoverLP);
        LinearLayout.LayoutParams mVideoLP = (LinearLayout.LayoutParams) mCard.mVideoParent.getLayoutParams();
        mVideoLP.width = Constant.toPix(720);
        mCard.mVideoParent.setLayoutParams(mVideoLP);
        mCard.mUserName = (TextView) view.findViewById(R.id.act_pk_user_name);
        mCard.mVideoTitle = (TextView) view.findViewById(R.id.act_pk_video_title);
        mCard.mVideoTime = (TextView) view.findViewById(R.id.act_pk_video_time);
        mCard.mSeekBar = new MaxSeekBar(getContext());
        LayoutParams mSeekBarLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mSeekBarLP.gravity = Gravity.CENTER;
        mCard.mVideoParent.addView(mCard.mSeekBar, mSeekBarLP);
        mCard.mController = new VideoController(getContext());
        mCard.mVideoView.setController(mCard.mController);
        mCard.mVideoView.setViewParams(mVideoLP.width, mVideoLP.height);
        mCard.mController.initControllerView(mCard.mSeekBar.mSeekHolder.mBtnPause, mCard.mSeekBar.mSeekHolder.mSeekbar, null, mCard.mVideoTime, true);
        mCard.mController.show();
        mCard.mVideoView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(IMediaPlayer mp) {
                if (null != mCard && null != mCard.mVideoCover) {
                    startVideoAnima(mCard.mVideoCover);
                }
            }
        });
//        mCard.mVideoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
//            @Override
//            public void onCompletion(IMediaPlayer mp) {
//                if (null != mCard && null != mCard.mVideoView) {
//                    mCard.mVideoView.start();
//                }
//            }
//        });
    }

    public void setOnCompletionListener(IMediaPlayer.OnCompletionListener l) {
        if (mCard != null && null != mCard.mVideoView) {
            mCard.mVideoView.setOnCompletionListener(l);
        }
    }

    public void clearListener() {
        if (mCard != null && null != mCard.mVideoView) {
            mCard.mVideoView.setOnCompletionListener(null);
        }
    }

    /**
     * 隐藏封面
     *
     * @param v
     */
    public void startVideoAnima(View v) {
        if (isAnimaStared || v == null) {
            return;
        }
        Animation mAlpaAnima = new AlphaAnimation(1.0f, 0.0f);
        mAlpaAnima.setDuration(300);
        mAlpaAnima.setFillEnabled(true);
        mAlpaAnima.setFillAfter(true);
        v.startAnimation(mAlpaAnima);
        isAnimaStared = true;
    }

    private void loadData() {
        if (null != mData && null != mCard) {
            if (!StringUtil.isNullorEmpty(mData.getVideoId())) {
                requestVideoUrl(mData.getVideoId());
            }
            Glide.with(getContext()).load(mData.getVideoImage()).centerCrop().into(mCard.mVideoCover);
            mCard.mUserName.setText(mData.getNickName());
            mCard.mVideoTitle.setText(getStageAction());
        }
    }
//    private void loadData(int delayMills) {
//        if (null != mData && null != mCard) {
//            if (!StringUtil.isNullorEmpty(mData.getVideoId())) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (null != mData && !StringUtil.isNullorEmpty(mData.getVideoId())) {
//                            requestVideoUrl(mData.getVideoId());
//                        }
//                    }
//                }, delayMills);
//            }
//            Glide.with(getContext()).load(mData.getVideoImage()).centerCrop().into(mCard.mVideoCover);
//            mCard.mUserName.setText(mData.getNickName());
//            mCard.mVideoTitle.setText(getStageAction());
//        }
//    }

    public String getStageAction() {
        return mStageAction;
    }

    public void setStageAction(String mStageAction) {
        this.mStageAction = mStageAction;
    }

    /**
     * Post请求视频地址
     *
     * @param key 视频文件名
     */
    private void requestVideoUrl(String key) {
        Map<String, String> requestBody = new FormEncodingBuilderEx()
                .add(Constant.KEY_MEDIAID, key)
                .add(Constant.KEY_RATE, "SD")
                .add(Constant.KEY_TYPE, "key")
                .add(Constant.KEY_USER_ID, MaxApplication.getInstance().getUid())
                .add(Constant.KEY_TOKEN, MaxApplication.getInstance().getToken())
                .build();
        post(BuildConfig.URL_GET_VIDEO_URL, requestBody);
    }

    /**
     * 跳转到登陆页面
     */
    public void jumpToLogin(String title) {
        MGTVUtil.getInstance().login(MaxApplication.getAppContext());
    }

    /**
     * 跳转到登陆页面
     */
    public void jumpToLogin(Intent intent) {
        MGTVUtil.getInstance().login(MaxApplication.getAppContext());
    }


    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {

    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url)) {
            try {
                //把code转成2开头
                String responseCode = resultModel.getResponseCode();
                if(!StringUtil.isNullorEmpty(responseCode)){
                    String subFirst = responseCode.substring(0,1);
                    responseCode = responseCode.replace(subFirst,"2");
                }
                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", responseCode, false);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        Log.i("JUNE", "url=" + url);
        Log.i("JUNE", "data=" + resultModel.getData());
        if (url.contains(BuildConfig.URL_GET_VIDEO_URL)) {
            VODModel vod = JSON.parseObject(resultModel.getData(),VODModel.class);
            if(vod != null){
                if(vod.isMgtvType()){
                    getVodUrl(vod.getPlayUrl());
                }else{
                    playVod(vod.getPlayUrl());
                }
            }
        }else if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));

                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", "", true);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    //点播类型为MGTV时缓存请求URl
    private String mVodRequestUrl;

    private void getVodUrl(String url){
        mVodRequestUrl = url;
        if(!StringUtil.isNullorEmpty(mVodRequestUrl)){
            get(url,null);
        }
    }

    private void playVod(String url){
        this.mVideoPath = url;
        if (isVideoStared) {
            startVideo();
        }
    }

    /**
     * 释放资源,解除耦合,减少内存的占用.
     */
    public void onDestory() {
        try {
            clearListener();
            stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            try {
                Glide.with(getContext()).onLowMemory();
            } catch (Exception e) {

            }
            try {
                mHttp.cancelAll();
                mHttp.setCallBack(null);
            } catch (Exception e) {

            }
            mHttp = null;
            mData = null;
            mVideoPath = null;
            mInflater = null;
            try {
                Glide.clear(mCard.mVideoCover);
            } catch (Exception e) {

            }
            mHandler = null;
            try {
                if (null != mCard) {
                    mCard.onDestory();
                    mCard = null;
                }
            } catch (Exception e) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public MaxSeekBar getmSeekBar() {
        if (mCard == null) {
            return null;
        }
        return mCard.mSeekBar;
    }

    class CardViewHolder {
        public VideoController mController;
        public FrameLayout mVideoParent;
        public IjkVideoView mVideoView;
        public ImageView mVideoCover;
        public TextView mUserName;
        public TextView mVideoTitle;
        public TextView mVideoTime;


        public MaxSeekBar mSeekBar;

        private void onDestory() {
            mController = null;
            mVideoParent = null;
            mVideoView = null;
            mVideoCover = null;
            mVideoTitle = null;
            mUserName = null;
            mVideoTime = null;
            mSeekBar = null;
        }
    }
}
